package com.chuantou.yuba.ui.fragment;

import java.util.Map;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ListAdapter;
import android.widget.Toast;

import com.android.volley.NoConnectionError;
import com.android.volley.Request.Method;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.TimeoutError;
import com.android.volley.VolleyError;
import com.chuantou.yuba.R;
import com.chuantou.yuba.api.RequestManager;
import com.chuantou.yuba.api.UriHelper;
import com.chuantou.yuba.api.request.BaseGsonRequest;
import com.chuantou.yuba.pojo.Pageable;
import com.chuantou.yuba.ui.widget.LoadingView;
import com.chuantou.yuba.ui.widget.LoadingView.Style;
import com.chuantou.yuba.ui.widget.xlist.XListView;
import com.chuantou.yuba.ui.widget.xlist.XListView.IXListViewListener;

/**
 * 自动分页的fragment
 * 
 * @author dl1001
 * 
 */
public abstract class PaginationListFragment<T extends Pageable> extends BaseFragment implements Listener<T>, ErrorListener {
	private View mContentView;
	protected XListView mListView;
	protected LoadingView mLoadingView;
	protected BaseGsonRequest<?> mRequest;
	private T mResponse;
	private String mParamsPageNO = UriHelper.PARAMS_PAGE_NO;

	@Override
	public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
		if (mContentView == null) {
			mContentView = inflater.inflate(R.layout.fg_pagenation_list, null);
			mListView = (XListView) mContentView.findViewById(android.R.id.list);
			mLoadingView = (LoadingView) mContentView.findViewById(android.R.id.empty);
			mLoadingView.setStyle(Style.LOADING, null);
			mLoadingView.setOnRetryListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					load(1);
				}
			});
			mListView.setEmptyView(mLoadingView);
			mListView.setXListViewListener(mListViewListener);
			mRequest = getRequest(this, this);
			if (mRequest.getMethod() != Method.POST) {
				throw new IllegalArgumentException("PaginationListFragment request method should be post");
			}
		}
		ViewGroup parentView = (ViewGroup) mContentView.getParent();
		if (parentView != null) {
			parentView.removeView(mContentView);
		}
		return mContentView;
	}

	protected void startRequest() {
		mLoadingView.setStyle(Style.LOADING, null);
		RequestManager.startRequest(mContext, mRequest);
	}

	IXListViewListener mListViewListener = new IXListViewListener() {

		@Override
		public void onRefresh() {
			load(1);
		}

		@Override
		public void onLoadMore() {
			int page = mResponse != null ? mResponse.getCurrentPage() + 1 : 1;
			load(page);
		}
	};

	protected void load(int page) {
		Map<String, String> params = mRequest.getParams();
		String pageNoKey = getPageNOKey();
		if (params != null) {
			params.put(pageNoKey, String.valueOf(page));
		}
		startRequest();
	}

	public void setPageNOKey(String key) {
		mParamsPageNO = key;
	}

	public String getPageNOKey() {
		return mParamsPageNO;
	}

	/**
	 * 获取网络请求
	 * 
	 * @return
	 */
	protected abstract BaseGsonRequest<T> getRequest(Listener<T> listener, ErrorListener errorListener);

	protected abstract String getEmptyString();

	/**
	 * 获取数据响应
	 * 
	 * @param response
	 */
	public void onResponse(T response) {
		if (getActivity() != null) {
			mListView.stopLoadMore();
			mListView.stopRefresh();
			ListAdapter adapter = mListView.getAdapter();
			int headerCount = adapter == null ? 0 : (mListView.getHeaderViewsCount() + mListView.getFooterViewsCount());
			if (response != null) {
				mResponse = response;
				mListView.setPullLoadEnable(mResponse.hasNextPage());
				if (adapter != null && (adapter.getCount() - headerCount) <= 0) {
					mLoadingView.setStyle(Style.EMPTY, getEmptyString());
				}
			} else {
				if (adapter != null && (adapter.getCount() - headerCount) > 0) {
					Toast.makeText(mContext, R.string.load_more_error, Toast.LENGTH_SHORT).show();
				} else {
					mLoadingView.setStyle(Style.ERROR, null);
				}
			}
		}
	}

	/**
	 * 获取数据错误时响应
	 * 
	 * @param error
	 */
	public void onErrorResponse(VolleyError error) {
		if (getActivity() != null) {
			ListAdapter adapter = mListView.getAdapter();
			mListView.stopLoadMore();
			mListView.stopRefresh();
			int headerCount = adapter == null ? 0 : (mListView.getHeaderViewsCount() + mListView.getFooterViewsCount());
			if (adapter != null && (adapter.getCount() - headerCount) > 0) {
				String errorMsg = mContext.getString(R.string.load_more_error);
				if (error instanceof NoConnectionError) {
					errorMsg = mContext.getString(R.string.network_error);
				} else if (error instanceof TimeoutError) {
					errorMsg = mContext.getString(R.string.timeout_error);
				}
				Toast.makeText(mContext, errorMsg, Toast.LENGTH_SHORT).show();
			} else {
				mLoadingView.setStyle(Style.ERROR, null);
			}
		}
	}

	protected void setBackgroundColor(int color) {
		mContentView.setBackgroundColor(color);
	}
}
